"""
datakit执行公共函数
"""

from yat.test import Node

from testcase.utils.datakit_api.CommonApi import CommonApi
from .Logger import Logger


class CommonDatakit:
    def __init__(self, token, node='datakit'):
        self.com_api = CommonApi(token)
        self.log = Logger()
        self.node = Node(node=node)

    def import_host(self, node_list: list):
        """
        快速导入服务器,如果服务器已存在则导入用户
        :param node_list: 需要导入的服务器节点的列表
        :return:
        """
        for node in node_list:
            response = self.com_api.get_host_page(name=f"{node.ssh_host}")
            self.log.info(response.json())
            if response.json()['total'] == 1:
                host_id = response.json()['rows'][0]['hostId']
                response = self.com_api.get_hostUser_page(host_id)
                self.log.info(response.json())
                if any(item['username'] == node.ssh_user for item in response.json()['rows']):
                    self.log.info(f"主机 {host_id} 已存在用户 {node.ssh_user}，跳过配置")
                    continue
                use_msg = {"hostId": f"{host_id}", "username": f"{node.ssh_user}",
                           "password": f"{node.ssh_password}"}
                self.log.info(use_msg)
                response = self.com_api.post_hostUser(use_msg)
                self.log.info(response.json())
                response = self.com_api.get_hostUser_page(host_id)
                self.log.info(response.json())
                assert response.text.find(node.ssh_user) >= -1
            else:
                data = {"hostId": "",
                        "isRemember": True,
                        "name": f"{node.ssh_host}",
                        "password": f"{node.ssh_password}",
                        "port": 22,
                        "privateIp": f"{node.ssh_host}",
                        "publicIp": f"{node.ssh_host}",
                        "remark": "",
                        "tags": [],
                        "username": f"{node.ssh_user}"}
                response = self.com_api.post_host(data)
                self.log.info(response.json())
                assert response.json()['code'] == 200
                response = self.com_api.get_host_page(name=f"{node.ssh_host}")
                self.log.info(response.json())
                assert response.json()['total'] == 1

    def delete_host(self):
        """
        快速删除已导入的服务器
        :return:
        """
        response = self.com_api.get_host_page()
        self.log.info(response.json())
        for cluster in response.json()['rows']:
            response = self.com_api.delete_host(cluster['hostId'])
            self.log.info(response.json())
            assert response.json()['code'] == 200
        res = self.com_api.get_host_page()
        self.log.info(res.json())
        return res

    def import_db(self, db_node_list: list):
        """
        快速导入数据库实例
        :param db_node_list: 数据库节点列表
        :return:
        """
        for db_node in db_node_list:
            if db_node.db_type == 'mysql':
                data = {"clusterName": f"{db_node.ssh_host}({db_node.db_port})-1",
                        "dbType": "MYSQL", "deployType": "SINGLE_NODE",
                        "nodes": [{"id": "", "tabName": 1,
                                   "url": f"jdbc:mysql://{db_node.ssh_host}:{db_node.db_port}",
                                   "urlSuffix": "", "ip": f"{db_node.ssh_host}",
                                   "port": db_node.db_port,
                                   "username": f"{db_node.db_user}",
                                   "password": f"{db_node.db_password}",
                                   "props": [{"name": "", "value": ""}], "status": 1,
                                   "extendProps": "[{\"name\":\"\",\"value\":\"\"}]"}]}
                self.log.info(data)
            else:
                data = {"clusterName": f"{db_node.ssh_host}({db_node.db_port})-1",
                        "dbType": "OPENGAUSS",
                        "deployType": "SINGLE_NODE",
                        "nodes": [{"id": "", "tabName": 1,
                                   "url": f"jdbc:opengauss://{db_node.ssh_host}:{db_node.db_port}/postgres",
                                   "urlSuffix": "", "ip": f"{db_node.ssh_host}",
                                   "port": db_node.db_port,
                                   "username": f"{db_node.db_user}",
                                   "password": f"{db_node.db_password}",
                                   "props": [{"name": "", "value": ""}], "status": 1,
                                   "extendProps": "[{\"name\":\"\",\"value\":\"\"}]"}]}
                self.log.info(data)
            response = self.com_api.post_jdbcDbCluster_add(data)
            self.log.info(response.json())
            assert response.json()['code'] == 200
            response = self.com_api.get_jdbcDbCluster_page(ip=db_node.ssh_host)
            self.log.info(response.json())
            assert response.json()['rows'] is not None

    def delete_db(self):
        """
        快速删除实例
        :return:
        """
        response = self.com_api.get_jdbcDbCluster_page()
        self.log.info(response.json())
        if response.json()['rows'] is None:
            return
        for db_cluster_msg in response.json()['rows']:
            for db_node in db_cluster_msg['nodes']:
                cluster_node_id = db_node['clusterNodeId']
                response = self.com_api.delete_jdbcDbCluster(cluster_node_id)
                self.log.info(response)
                assert response.json()['code'] == 200
        response = self.com_api.get_jdbcDbCluster_page()
        self.log.info(response.json())
        assert response.json()['rows'] == []


